package com.pig4cloud.pig.ads.controller.gdt;

import java.util.Arrays;
import java.util.List;

import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pig4cloud.pig.ads.gdt.service.GdtCustomAudiencesFileService;
import com.pig4cloud.pig.ads.gdt.service.GdtCustomAudiencesService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtCustomAudienceService;
import com.pig4cloud.pig.api.entity.TtCustomAudience;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.api.gdt.dto.GdtCustomAudiencesDto;
import com.pig4cloud.pig.api.gdt.dto.GdtCustomAudiencesListDto;
import com.pig4cloud.pig.api.gdt.entity.GdtCustomAudiences;
import com.pig4cloud.pig.api.gdt.entity.GdtCustomAudiencesFile;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.util.SecurityUtils;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

/**
 * @projectName:pig
 * @description:广点通人群管理
 * @author:Zhihao
 * @createTime:2020/12/4 15:58
 * @version:1.0
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/gdt/customAudiences")
@Api(value = "/gdt/customAudiences", tags = "广点通客户群体管理模块")
public class GdtCustomAudiencesController {

	private final TtCustomAudienceService ttCustomAudienceService;

	private final GdtCustomAudiencesService gdtCustomAudiencesService;

	private final GdtCustomAudiencesFileService gdtCustomAudiencesFileService;

	private final AdvService advService;

	/**
	 * 分页查询客户群体列表
	 *
	 * @return 分页对象
	 */
	@PostMapping("/page")
	public R page(@RequestBody GdtCustomAudiencesListDto dto) {

		if (dto == null) {
			return R.failed("搜索参数不能为空");
		}
		if (null == dto.getPage()) {
			return R.failed("未获取到分页参数！");
		}


		List<String> adList = advService.getOwnerAdv(SecurityUtils.getUser().getId(), PlatformTypeEnum.GDT.getValue());
		if(adList == null || adList.size() == 0) {
			return R.ok(new Page());
		}

		//设置where条件
		QueryWrapper<GdtCustomAudiences> queryWrapper = new QueryWrapper<>();

		//推广账户Id
		if (dto.getAccountIds() != null && dto.getAccountIds().length != 0) {
			//多个账户之间逗号分隔
			queryWrapper.in("account_id", Arrays.asList(dto.getAccountIds()));
		}

		//搜索名称/ID
		if (StringUtils.isNotBlank(dto.getSearchName())) {
			queryWrapper.like("name", dto.getSearchName()).or().like("audience_id", dto.getSearchName());
		}

		//搜索名称/ID
		if (StringUtils.isNotBlank(dto.getType())) {
			queryWrapper.eq("type", dto.getType());
		}

		//状态
		if (StringUtils.isNotBlank(dto.getStatus())) {
			queryWrapper.eq("status", dto.getStatus());
		}

		//时间区间范围
		String sdate = dto.getSdate();
		String edate = dto.getEdate();
		queryWrapper.apply(StringUtils.isNotBlank(sdate),
                "date_format (created_time,'%Y-%m-%d') >= date_format('" + sdate + "','%Y-%m-%d')");
		queryWrapper.apply(StringUtils.isNotBlank(edate),
                "date_format (created_time,'%Y-%m-%d') <= date_format('" + edate + "','%Y-%m-%d')");


		//覆盖数量 1： 10w-100w   2：100w-500w   3:500w以上
		//lt：小于 le：小于等于 eq：等于 ne：不等于 ge：大于等于 gt：大于
		queryWrapper.and(dto.getCoverNumType() != null && dto.getCoverNumType() == 1, wrapper -> wrapper.ge("user_count", 100000).lt("user_count", 1000000));
		queryWrapper.and(dto.getCoverNumType() != null && dto.getCoverNumType() == 2, wrapper -> wrapper.ge("user_count", 1000000).lt("user_count", 5000000));
		queryWrapper.and(dto.getCoverNumType() != null && dto.getCoverNumType() == 3, wrapper -> wrapper.ge("user_count", 5000000));

		//只查询自身名下广点通账号的数据
		queryWrapper.in("account_id", adList);

		//根据创建时间降序
		queryWrapper.orderByDesc("created_time");

		return R.ok(gdtCustomAudiencesService.page(dto.getPage(), queryWrapper));
	}


	/**
	 * 分页查询广点通客户群体文件列表
	 *
	 * @return
	 */
	@GetMapping("/fileList")
	public R fileList(Page page, String audienceId) {
		if (StringUtils.isEmpty(audienceId)) {
			return R.failed("未获取到客户人群ID！");
		}
		if (null == page) {
			return R.failed("未获取到分页参数！");
		}
		//设置where条件
		QueryWrapper<GdtCustomAudiencesFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("audience_id", audienceId);
		return R.ok(gdtCustomAudiencesFileService.page(page, queryWrapper));
	}

	/**
	 * 上传人群包
	 *
	 * @param customFile
	 * @return
	 */
	@RequestMapping("/uploadCustomAudiencesFile")
	public R uploadCustomAudiencesFile(MultipartFile[] customFile, @Valid GdtCustomAudiencesDto gdtCustomAudiencesDto) {

		if (gdtCustomAudiencesDto == null) {
			return R.failed("未获取到人群信息！");
		}

		if (customFile == null || customFile.length == 0) {
			return R.failed("未获取到文件信息！");
		}
		LambdaQueryWrapper<TtCustomAudience> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(TtCustomAudience::getMediaType,PlatformTypeEnum.GDT.getValue()));
		query.and(wrapper -> wrapper.eq(TtCustomAudience::getName, gdtCustomAudiencesDto.getName()));
		List<TtCustomAudience> list = ttCustomAudienceService.list(query);
		if (!CollectionUtils.isEmpty(list)) {
			return R.failed("人群包名称已存在!");
		}
		return gdtCustomAudiencesService.uploadCustomAudiencesFile(customFile, gdtCustomAudiencesDto);
	}

}
